package cn.edu.zjicm.wordsnet_d.view;

import java.util.Arrays;
import java.util.Calendar;

import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.SelectStudyModeActivity;
import cn.edu.zjicm.wordsnet_d.data.StudyPlan;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class SettingPlanDialog {
	private View view;
	private TextView numberTv;
	private ViewFlipper mFlipper;
	// private WheelView numberWheel;
	private MyWheelView numberWheel;
	private AlertDialog dialog;
	private DatePicker endTimePicker;

	private SelectStudyModeActivity mContext;
	private int studyMode; // 学习模式，是按照截止时间还是按照每天学习个数
	private int bookIndex;
	private int bookType; // 选择的书类别，是单词还是词组
	private Calendar minDate, maxDate;
	private String[] numberArray = new String[] { "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "60", "70", "80", "90", "100", "125", "150", "175", "200", "225", "250", "275", "300",
			"325", "350", "375", "400", "450", "500", "550", "600" };
	private int unlearnedWordNum; // 这本单词书的未学单词
	private int selectYear, selectMonth, selectDay;
	private int everydayNumber = 50;

	public SettingPlanDialog(SelectStudyModeActivity mContext, int studyMode, int bookType, int bookIndex, int unlearnWordCount) {
		this.mContext = mContext;
		this.studyMode = studyMode;
		this.bookIndex = bookIndex;
		this.bookType = bookType;
		this.unlearnedWordNum = unlearnWordCount;

		findView();
		initView();
		showDialog();
	}

	private void findView() {
		view = View.inflate(mContext, R.layout.view_setting_plan_dialog, null);
		numberTv = (TextView) view.findViewById(R.id.numberTv);
		mFlipper = (ViewFlipper) view.findViewById(R.id.flipper);
		endTimePicker = (DatePicker) view.findViewById(R.id.end_time_picker);
		numberWheel = (MyWheelView) view.findViewById(R.id.number_wheel);
	}

	private void showDialog() {

		mContext.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		// , R.style.animation_for_share_dialog);// 这里应用了你的自定义样式
		// dialog.setCanceledOnTouchOutside(false);
		view.setMinimumWidth(Utils.getScreenWidth(mContext));

		// WindowManager.LayoutParams layoutParams =
		// dialog.getWindow().getAttributes();
		// layoutParams.x = 0;
		// final int cMakeBottom = -1000;
		// layoutParams.y = cMakeBottom;
		// layoutParams.gravity = Gravity.BOTTOM;
		// dialog.onWindowAttributesChanged(layoutParams);
		String dialogTitle;
		if (studyMode == AppPreference.StudyMode.MODE_END_TIME) {
			dialogTitle = "截止日期";
		} else {
			dialogTitle = "固定词量";
			// view.setBackgroundResource(R.drawable.setting_paln_dialog_bg);
		}
		dialog = new AlertDialog.Builder(mContext).setTitle(dialogTitle).setView(view).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				saveStudyPlan();
			}
		}).setNegativeButton("取消", null).create();

		dialog.show();

		// InputMethodManager imm = (InputMethodManager)
		// mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		// boolean isOpen = imm.isActive();
		// System.out.println("isOpen-->"+isOpen);
		// if (isOpen) {
		// // imm.toggleSoftInput(0,
		// // InputMethodManager.HIDE_NOT_ALWAYS);
		// //
		// imm.hideSoftInputFromWindow(mContext.getCurrentFocus().getWindowToken(),
		// InputMethodManager.HIDE_NOT_ALWAYS);
		// imm.hideSoftInputFromWindow( endTimePicker.getWindowToken(),
		// InputMethodManager.HIDE_NOT_ALWAYS);
		// }
		handler.obtainMessage(0).sendToTarget();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
				endTimePicker.setEnabled(true);
			}
		}
	};

	private void initView() {
		if (studyMode == AppPreference.StudyMode.MODE_END_TIME) {
			mFlipper.setDisplayedChild(0);
			initForEndTime();
		} else {
			mFlipper.setDisplayedChild(1);
			initForNumber();
		}
	}

	protected void saveStudyPlan() {
		StudyPlan studyPlan = new StudyPlan();
		LogUtil.d("在dialog中,bookIndex=" + bookIndex);
		studyPlan.setBookIndex(bookIndex);
		studyPlan.setBookType(bookType);
		studyPlan.setStudyMode(studyMode);
		studyPlan.setLearning(true);
		studyPlan.setStartPlanTime(DateTimeUtils.getDate());

		if (studyMode == AppPreference.StudyMode.MODE_END_TIME) {
			studyPlan.setEndYear(selectYear);
			studyPlan.setEndMonth(selectMonth);
			studyPlan.setEndDay(selectDay);
		} else {
			if (everydayNumber > unlearnedWordNum)
				everydayNumber = unlearnedWordNum;
			studyPlan.setEveryDayNumber(everydayNumber);
		}

		// studyPlan.savePlan(mContext); //在点击开始学习时，再保存到AppPreference中
		mContext.showPlanDetail(studyPlan);
	}

	private void initForEndTime() {
		Calendar today = Calendar.getInstance();

		selectYear = today.get(Calendar.YEAR);
		selectMonth = today.get(Calendar.MONTH) + 2;
		if (selectMonth >= 12) {
			selectMonth = selectMonth - 12;
			selectYear++;
		}

		selectDay = today.get(Calendar.DAY_OF_MONTH);
		int dayOfMonth = DateTimeUtils.getDaysOfMonth(selectYear, selectMonth + 1);
		if (selectDay > dayOfMonth) {
			selectDay = dayOfMonth;
		}

		int suitableDays = DateTimeUtils.getSuitableDays(mContext, bookIndex);
		minDate = Calendar.getInstance();
		minDate.add(Calendar.DATE, suitableDays); // 一天最多600个单词的天数
		maxDate = Calendar.getInstance();
		maxDate.add(Calendar.YEAR, 1); // 最多学习一年

		updateNumberTv(selectYear, selectMonth, selectDay);
		endTimePicker.setEnabled(false);
		endTimePicker.setDescendantFocusability(DatePicker.FOCUS_AFTER_DESCENDANTS);
		endTimePicker.init(selectYear, selectMonth, selectDay, onDateChangedListener);

		// Log.i("date",
		// today.get(Calendar.YEAR)+","+today.get(Calendar.MONTH)+","+today.get(Calendar.DAY_OF_MONTH));
		// Log.i("mindate",
		// minDate.get(Calendar.YEAR)+","+minDate.get(Calendar.MONTH)+","+minDate.get(Calendar.DAY_OF_MONTH));
		// Log.i("maxdate",
		// maxDate.get(Calendar.YEAR)+","+maxDate.get(Calendar.MONTH)+","+maxDate.get(Calendar.DAY_OF_MONTH));
	}

	OnDateChangedListener onDateChangedListener = new OnDateChangedListener() {

		@Override
		public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			Calendar newDate = Calendar.getInstance();
			newDate.set(year, monthOfYear, dayOfMonth);

			if (minDate != null && isDateBefore(newDate)) {
				view.init(minDate.get(Calendar.YEAR), minDate.get(Calendar.MONTH), minDate.get(Calendar.DAY_OF_MONTH), this);
				Toast.makeText(mContext, "每天单词学习数量不能超过600个", Toast.LENGTH_SHORT).show();

			} else if (maxDate != null && isDateAfter(newDate)) {
				view.init(maxDate.get(Calendar.YEAR), maxDate.get(Calendar.MONTH), maxDate.get(Calendar.DAY_OF_MONTH), this);
				Toast.makeText(mContext, "学习周期不能超过一年", Toast.LENGTH_SHORT).show();

			} else {
				view.init(year, monthOfYear, dayOfMonth, this);
			}

			updateNumberTv(year, monthOfYear, dayOfMonth);
		}
	};

	/**
	 * 根据截止日期来更新
	 * 
	 * @param year
	 * @param monthOfYear
	 * @param dayOfMonth
	 */
	private void updateNumberTv(int year, int monthOfYear, int dayOfMonth) {
		int wordsNumPerDay = DateTimeUtils.getWordsNumberPerDayForPlan2(unlearnedWordNum, mContext, year, monthOfYear, dayOfMonth);
		String info = "预计每日学习 " + wordsNumPerDay + " 个";
		numberTv.setText(info);
		setTextViewSpan(numberTv, Utils.changeDipToPx(mContext, 23), 6, info.length() - 1, Color.BLACK);
		selectYear = year;
		selectMonth = monthOfYear;
		selectDay = dayOfMonth;
	}

	public void setTextViewSpan(TextView view, int fontSize, int start, int end, int color) {

		Spannable span = new SpannableString(view.getText());
		span.setSpan(new AbsoluteSizeSpan(fontSize), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		view.setText(span);
	}

	/**
	 * 根据每天学习个数来更新
	 * 
	 * @param everydayNumber
	 */
	private void updateNumberTv() {
		int days = DateTimeUtils.getDaysByStudyNumPerDay(unlearnedWordNum, everydayNumber);
		String info = "预计完成时间 " + days + " 天";
		numberTv.setText(info);
		setTextViewSpan(numberTv, Utils.changeDipToPx(mContext, 23), 6, info.length() - 1, Color.BLACK);
	}

	private boolean isDateBefore(Calendar planEndDate) {
		return planEndDate.getTimeInMillis() / 1000 / 60 / 60 / 24 - minDate.getTimeInMillis() / 1000 / 60 / 60 / 24 < 0;
	}

	private boolean isDateAfter(Calendar planEndDate) {
		return planEndDate.getTimeInMillis() / 1000 / 60 / 60 / 24 - maxDate.getTimeInMillis() / 1000 / 60 / 60 / 24 > 0;
	}

	private void initForNumber() {
		updateNumberTv();

		numberWheel.setOffset(1);
		numberWheel.setItems(Arrays.asList(numberArray));
		numberWheel.setSeletion(9);
		numberWheel.setOnWheelViewListener(new MyWheelView.OnWheelViewListener() {
			@Override
			public void onSelected(int selectedIndex, String item) {
				everydayNumber = Integer.valueOf(numberArray[selectedIndex]);
				updateNumberTv();
			}
		});

		// ArrayWheelAdapter<String> numberAdapter = new
		// ArrayWheelAdapter<String>(mContext, numberArray);
		// numberAdapter.setItemResource(R.layout.view_wheel_text_item);
		// numberAdapter.setItemTextResource(R.id.text);
		// numberAdapter.setEmptyItemResource(R.layout.view_wheel_text_item);
		// numberWheel.setViewAdapter(numberAdapter);
		// numberWheel.setCurrentItem(9); // 设置默认显示50
		// numberWheel.addChangingListener(new OnWheelChangedListener() {
		//
		// @Override
		// public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// everydayNumber = Integer.valueOf(numberArray[newValue]);
		// updateNumberTv();
		// }
		// });
	}
}
